
package org.kth.dks.dks_dht;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.kth.dks.DKSObject;
import org.kth.dks.dks_marshal.DKSMessage;
import org.kth.dks.dks_node.Interval;


public class DHTRestoreItemsMsg extends DKSMessage {
    public final static String NAME= "LOSTITEMSMSG";

    private List tripletEntries = null;
    private List intervals      = null; 
    private int  cc = -10;
    private int  id; 
    
    public String getName() { return NAME; }
    public List getTripletList() { return tripletEntries; }
    public List getIntervals() { return intervals; }
    public int  getCC() { return cc;}
    public int  getId() {return id;}

    public  DHTRestoreItemsMsg(){

    }

   public  DHTRestoreItemsMsg(int c, int id, List te, List in) {
	this.tripletEntries  = te;
	this.intervals       = in; 
	this.cc              = c; 
	this.id              = id; 
    }

    public void marshal() throws IOException {
	marshaler.addInt(cc, "cc");
	marshaler.addInt(id, "id");
	marshaler.addInt(tripletEntries.size(), "tripsize");
	int cnt = 1;
	for (Iterator it = tripletEntries.iterator(); it.hasNext(); ) {
	    StoreTriplet curr = (StoreTriplet) it.next();
	    marshaler.addLong(curr.key.longValue(), "key"+cnt);
	    marshaler.addInt(curr.index, "index"+cnt);
	    marshaler.addDKSObject(curr.obj, "obj"+cnt);
	    cnt++;
	}
	marshaler.addInt(intervals.size(), "intervalsize");
	cnt = 1; 
	for(Iterator iter2 = intervals.iterator(); iter2.hasNext();){
	    Interval in = (Interval) iter2.next();
	    marshaler.addLong(in.start, "start"+cnt);
	    marshaler.addLong(in.end, "end"+cnt);
	    cnt++; 
	}
    }

    public void unmarshal() throws IOException {
      cc    = marshaler.remInt("cc");
      id    = marshaler.remInt("id");
      int tripSize = marshaler.remInt("tripsize");
      int cnt = 1;
      tripletEntries = new ArrayList();
      for (cnt = 1; cnt<=tripSize; cnt++) {
        long k      = marshaler.remLong("key"+cnt);
        int i       = marshaler.remInt("index"+cnt);
        DKSObject o = marshaler.remDKSObject("obj"+cnt);
        tripletEntries.add( new StoreTriplet(i, new Long(k), o) );
      }
      
      int sz = marshaler.remInt("intervalsize");
      intervals = new ArrayList();
      for (int cnt0 = 1; cnt0 <= sz; cnt0++) {
	  long start      = marshaler.remLong("start"+cnt0);
	  long end       =  marshaler.remLong("end"+cnt0);
	  intervals.add(new Interval(start, end));
      }
    }
}

